package com.dwfyc.hibernate;

import java.util.List;

import org.hibernate.FetchMode;
import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * A data access object (DAO) providing persistence and search support for
 * Documento entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.dwfyc.hibernate.Documento
 * @author MyEclipse Persistence Tools
 */

public class DocumentoDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory
			.getLogger(DocumentoDAO.class);
	// property constants
	public static final String NOMBRE = "nombre";
	public static final String DESCRIPCION = "descripcion";
	public static final String CADUCIDAD = "caducidad";
	public static final String ES_COMUN_OBRAS = "esComunObras";
	public static final String FECHA_ALTA = "fechaAlta";
	public static final String FECHA_BAJA = "fechaBaja";

	protected void initDao() {
		// do nothing
	}

/**
	 * save Persists an entity. Will assign an identifier if one doesn't exist.
	 * If one does, it's essentially doing an update. Returns the generated ID
	 * of the entity.
	 * 
	 * @param transientInstance
	 * @throws RuntimeException
	 */
	public void save(Documento transientInstance) {
		log.debug("saving Documento instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Documento persistentInstance) {
		log.debug("deleting Documento instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Documento findById(java.lang.Integer id) {
		log.debug("getting Documento instance with id: " + id);
		try {
			Documento instance = (Documento) getHibernateTemplate().get(
					"com.dwfyc.hibernate.Documento", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Documento> findDocumentosActivos() throws RuntimeException {
		log.debug("getting Documentos Activos ");

		String queryString = "from Documento as model where model.fechaBaja is null";
		return getHibernateTemplate().find(queryString);

	}

	@SuppressWarnings("unchecked")
	public List<Documento> findByExample(Documento instance) {
		log.debug("finding Documento instance by example");
		try {
			List<Documento> results = (List<Documento>) getHibernateTemplate()
					.findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Documento> findByProperty(String propertyName, Object value) {
		log.debug("finding Documento instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Documento as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	
	public List<Documento> findByFechaAlta(Object fechaAlta) {
		return findByProperty(FECHA_ALTA, fechaAlta);
	}

	public List<Documento> findByFechaBaja(Object fechaBaja) {
		return findByProperty(FECHA_BAJA, fechaBaja);
	}

	public List<Documento> findByNombre(Object nombre) {
		return findByProperty(NOMBRE, nombre);
	}

	public List<Documento> findByDescripcion(Object descripcion) {
		return findByProperty(DESCRIPCION, descripcion);
	}

	public List<Documento> findByCaducidad(Object caducidad) {
		return findByProperty(CADUCIDAD, caducidad);
	}

	public List<Documento> findByEsComunObras(Object esComunObras) {
		return findByProperty(ES_COMUN_OBRAS, esComunObras);
	}

	@SuppressWarnings("unchecked")
	public List<Documento> findAll() {
		log.debug("finding all Documento instances");
		try {
			String queryString = "from Documento";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

@SuppressWarnings("unchecked")
public List<Documento> findAllWithTypes() {
		/*
		 * Criteria consulta = getSession().createCriteria(
		 * "com.atrium.hibernate.Usuarios"); consulta.setFetchMode("roles",
		 * FetchMode.JOIN); List<Usuarios> lista = consulta.list(); return
		 * lista;
		 */

		// OBLIGATORIO EL USO PARA SPRING
		DetachedCriteria consulta = DetachedCriteria
				.forEntityName("com.dwfyc.hibernate.Documento");
		consulta.setFetchMode("tipos", FetchMode.JOIN);
		List<Documento> listaDoc = getHibernateTemplate().findByCriteria(
				consulta);
		return listaDoc;
	}

/**
	 * merge Now this is where my knowledge starts to falter. The important
	 * thing here is the difference between transient, detached and persistant
	 * entities. For more info on the object states, take a look here. With save
	 * & update, you are dealing with persistant objects. They are linked to a
	 * Session so Hibernate knows what has changed. But when you have a
	 * transient object, there is no session involved. In these cases you need
	 * to use merge for updates and persist for saviing.
	 * 
	 * @param detachedInstance
	 * @return
	 * @throws RuntimeException
	 */
	public Documento merge(Documento detachedInstance) {
		log.debug("merging Documento instance");
		try {
			Documento result = (Documento) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

/**
	 * saveOrUpdate Calls either save or update depending on some checks. E.g.
	 * if no identifier exists, save is called. Otherwise update is called.
	 * 
	 * @param instance
	 * @throws RuntimeException
	 */
	public void attachDirty(Documento instance) {
		log.debug("attaching dirty Documento instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Documento instance) {
		log.debug("attaching clean Documento instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static DocumentoDAO getFromApplicationContext(ApplicationContext ctx) {
		return (DocumentoDAO) ctx.getBean("DocumentoDAO");
	}
}